﻿using Microsoft.Extensions.DependencyInjection;

namespace EventHandlerDemo.Domain.Bases.UOW
{
    public class UnitOfWorkManager : IUnitOfWorkManager
    {
        private readonly ICurrentUnitOfWorkProvider _currentUnitOfWorkProvider;
        private readonly IServiceProvider _serviceProvider;

        public IOuterUnitOfWork Current
        {
            get { return _currentUnitOfWorkProvider.Current; }
        }

        public UnitOfWorkManager(
            ICurrentUnitOfWorkProvider currentUnitOfWorkProvider,
            IServiceProvider serviceProvider)
        {
            _currentUnitOfWorkProvider = currentUnitOfWorkProvider;
            _serviceProvider = serviceProvider;
        }

        public IUnitOfWorkBase Begin()
        {
            var outerUow = _currentUnitOfWorkProvider.Current;

            if (outerUow != null)
            {
                return new InnerUnitOfWork(outerUow);
            }

            var uow = _serviceProvider.GetService<IOuterUnitOfWork>();

            uow.BeginTransaction();

            _currentUnitOfWorkProvider.Current = uow;

            return uow;
        }
    }
}
